package cn.yhjz.platform.system.config.security;

import cn.yhjz.common.AjaxResponse;
import cn.yhjz.platform.system.entity.LogedUserDetails;
import cn.yhjz.platform.system.entity.SysUser;
import cn.yhjz.platform.system.repository.UserPrincipalRepository;
import cn.yhjz.platform.system.service.ISysUserService;
import cn.yhjz.platform.system.util.TokenUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

@Slf4j
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private UserPrincipalRepository userPrincipalRepository;

    /**
     * @param request
     * @param response
     * @param authentication 已登录用户的信息，User类型
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //登录成功之后，转换对象之后存储到session中
        HttpSession session = request.getSession();
        LogedUserDetails principal = (LogedUserDetails) authentication.getPrincipal();
        String username = principal.getUsername();
        //查询用户信息
        SysUser queryParam = new SysUser();
        queryParam.setUsername(username);
        SysUser sysUser = sysUserService.selectOne(queryParam);
        //更新最后登录时间
        SysUser updateParam = new SysUser();
        updateParam.setId(sysUser.getId());
        updateParam.setLastLoginTime(new Date());
        sysUserService.updateById(updateParam);
        // 生成jwt
        String token = tokenUtil.createToken(sysUser);
        principal.setSysUser(sysUser);
        //把用户验证和授权信息存入redis
        userPrincipalRepository.save(sysUser.getUserCode(), principal);
        AjaxResponse res = AjaxResponse.success("success");
        res.setData(token);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONUtil.toJsonStr(res));
    }
}
